package top.jacktgq.lock.reentrantLock;

import top.jacktgq.utils.LogUtils;

/**
 * 
 * @Title: TestReentrantLock.java 
 * @Package top.jacktgq.lock 
 * @Description: 多线程交替输出：线程1输出 a 5次，线程2输出 b 5次，线程3输出 c 5次
 * @author CandyWall   
 * @date 2020年11月1日 下午5:49:07 
 * @version V1.0
 */
public class Demo6_2_multiThreadRunInTurn {
	public static void main(String[] args) {
		WaitNotify wn = new WaitNotify(1, 5);
		new Thread(() -> {
			wn.print("a", 1, 2);
		}, "t1").start();
		new Thread(() -> {
			wn.print("b", 2, 3);
		}, "t2").start();
		new Thread(() -> {
			wn.print("c", 3, 1);
		}, "t3").start();
	}	
}

/*
 *	输出内容	等待标记	下一个标记 
 * 	   a	  1		   2
 *     b      2        3
 *     c      3        1
 */
class WaitNotify {
	//等待标记
	private int flag;
	//循环次数
	private int loopNumber;
	public WaitNotify(int flag, int loopNumber) {
		this.flag = flag;
		this.loopNumber = loopNumber;
	}
	
	public void print(String str, int waitFlag, int nextFlag) {
		for(int i = 0; i < loopNumber; i++) {
			synchronized (this) {
				//等待标记不一致就进入等待
				while(flag != waitFlag) {
					try {
						this.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				LogUtils.log("WaitNotify", str);
				flag = nextFlag;
				this.notifyAll();
			}
		}
	}
}
